var EditForm = EventDispatcher.extend({

	form: null,
	formFields: null,
	deleteLink: null,
	ajaxCreateHandlerUrl: null,
	ajaxUpdateHandlerUrl: null,
	ajaxDeleteHandlerUrl: null,

	constructor: function(isUpdateForm)
	{
		this.form = $('form');
		this.formFields = this.form.find(':input').not('input[type="submit"]');
		this.deleteLink = $('#delete');
		this.ajaxCreateHandlerUrl = $('#ajaxCreateHandlerUrl').text();
		this.ajaxUpdateHandlerUrl = $('#ajaxUpdateHandlerUrl').text();
		this.ajaxDeleteHandlerUrl = $('#ajaxDeleteHandlerUrl').text();
		if (isUpdateForm)
		{
			this.form.bind('submit', handler(this, 'updateSubmitHandler'));
			this.deleteLink.bind('click', handler(this, 'deleteHandler'));
		}
		else
		{
			this.form.bind('submit', handler(this, 'createSubmitHandler'));
		}
	},

	getFormValues: function()
	{
		var formValues = {};

		this.formFields.each(
			function()
			{
				var el = $(this);
				formValues[el.attr('name')] = el.val();
			}
		);
		return formValues;
	},

	createSubmitHandler: function(evt)
	{
		var formValues = this.getFormValues();

		$.post(
			this.ajaxCreateHandlerUrl,
			formValues,
			handler(this, 'createAjaxResponceHandler')
		);

		return false;
	},

	updateSubmitHandler: function(evt)
	{
		var formValues = this.getFormValues();

		$.post(
			this.ajaxUpdateHandlerUrl,
			formValues,
			handler(this, 'updateAjaxResponceHandler')
		);

		return false;
	},

	deleteHandler: function(evt)
	{
		evt.preventDefault();

		$.post(
			this.ajaxDeleteHandlerUrl,
			{spider_result_id: this.deleteLink.attr('tabindex')},
			handler(this, 'deleteAjaxResponceHandler')
		);
	},

	createAjaxResponceHandler: function(resp)
	{
		if (resp === '1')
		{
			this.dispatchEvent('create');
		}
		else
		{
			alert(resp);
		}
	},

	updateAjaxResponceHandler: function(resp)
	{
		if (resp === '1')
		{
			this.dispatchEvent('update');
		}
		else
		{
			alert(resp);
		}
	},

	deleteAjaxResponceHandler: function(resp)
	{
		if (resp === '1')
		{
			this.dispatchEvent('delete');
		}
		else
		{
			alert("Error: Form deletion failed.");
		}
	}
});